package com.muk.meis.util;

import java.io.StringWriter;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.transform.OutputKeys;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerConfigurationException;
import javax.xml.transform.TransformerException;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;

import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Text;

public class XMLUtil {
	private DocumentBuilder docBuilde;
	private Document doc;
	private Element root;
	
	public XMLUtil() {
        DocumentBuilderFactory dbfac = DocumentBuilderFactory.newInstance();
        DocumentBuilder docBuilder;
		try {
			docBuilder = dbfac.newDocumentBuilder();
			doc = docBuilder.newDocument();
		} catch (ParserConfigurationException e) {
			e.printStackTrace();
		}
	}
	
	public Document getDocument(){
		return doc;
	}
	
	public void createRoot(String tagName){
		root = doc.createElement(tagName);
		doc.appendChild(root);
	}
	
	public Element createChild(String tagName) {
		Element child = doc.createElement(tagName);
		root.appendChild(child);
		return child;
	}
	
	public Text createText(String value){
		Text text = doc.createTextNode(value);
		return text;
	}
	
	@Override
	public String toString() {
        TransformerFactory transfac = TransformerFactory.newInstance();
        Transformer trans;
        String xmlString = null;
        System.out.println(root);
		try {
			trans = transfac.newTransformer();			
	        //create string from xml tree
            trans.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes");
            trans.setOutputProperty(OutputKeys.INDENT, "yes");			
	        StringWriter sw = new StringWriter();
	        StreamResult result = new StreamResult(sw);
	        DOMSource source = new DOMSource(this.doc);
	        trans.transform(source, result);
	        xmlString = sw.toString();				
		} catch (TransformerConfigurationException e) {
			e.printStackTrace();
		} catch (TransformerException e) {
			e.printStackTrace();
		}

		return xmlString;
	}
	
	public static void main(String[] args) {
		XMLUtil obj = new XMLUtil();
		obj.createRoot("chart");
		Element childTag = obj.createChild("series");	
		Element valueTag = obj.createChild("value");
		Text text = obj.createText("21 Jan");
		valueTag.appendChild(text);
		childTag.appendChild(valueTag);
		System.out.println(obj);
	}
	
	

}
